import uuid
import helpers.FileHelper as FileHelper
import helpers.MiscHelper as MiscHelper


class PackageInterface:

    def __init__(self, root_path, conf):
        self.path = root_path
        self.conf = conf

    def setup(self, opts):
        pass

    def rehash(self, version=None):
        pid = uuid.uuid1().hex
        MiscHelper.json_set(self.conf, pid, "name")
        if version is not None and MiscHelper.compare_version(MiscHelper.json_get(self.conf, "version"), version) < 0:
            MiscHelper.json_set(self.conf, version, "version")
        FileHelper.w_json(self.conf, self.path, "config.json")
        FileHelper.filter_dir(self.path, [FileHelper.SuffixFilter({"lua"})], lambda a, b, c: self._replace_pid(pid, a))

    def sign(self):
        extra = {}
        if FileHelper.exists(self.path, "extra.json"):
            extra = FileHelper.r_json(self.path, "extra.json")
        sign = MiscHelper.json_get(extra, "External_Producer")
        if type(sign) != bool or not sign:
            extra["External_Producer"] = True
            FileHelper.w_json(extra, self.path, "extra.json")

    @staticmethod
    def _replace_pid(pid, full_path):
        lines = FileHelper.r_line(full_path)
        changed = False
        for i, line in enumerate(lines):
            data = line.lstrip()
            if data.startswith("local ___PID___ ="):
                lines[i] = '{}local ___PID___ = "{}"\n'.format(" " * (len(line) - len(data)), pid)
                changed = True
        if changed:
            FileHelper.w_line(lines, full_path, break_line=False)
